package com.dlc.shop.seckill.common.listener;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dlc.shop.bean.event.RefundStockSuccessEvent;
import com.dlc.shop.bean.vo.SkuStockVO;
import com.dlc.shop.common.enums.StatusEnum;
import com.dlc.shop.manager.impl.StockManager;
import com.dlc.shop.seckill.common.model.Seckill;
import com.dlc.shop.seckill.common.service.SeckillService;
import com.dlc.shop.util.StockUtil;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 退款订单监听
 * @author lhd
 */
@Component("refundStockSuccessListener")
@AllArgsConstructor
public class RefundStockSuccessListener {

    private final StockManager stockManager;

    private final SeckillService seckillService;


    /**
     * 退还用户此笔退款订单使用的优惠券
     */
    @EventListener(RefundStockSuccessEvent.class)
    public void seckillRefundStockSuccessEvent(RefundStockSuccessEvent event) {
        List<SkuStockVO> skuStockList = event.getSkuStockList();
        if (CollUtil.isEmpty(skuStockList)) {
            return;
        }
        Set<Long> seckillIds = skuStockList.stream().map(SkuStockVO::getActivityId).collect(Collectors.toSet());
        List<Seckill> seckillList = seckillService.list(new LambdaQueryWrapper<Seckill>()
                .in(Seckill::getSeckillId, seckillIds)
                .eq(Seckill::getStatus, StatusEnum.ENABLE.value())
                .eq(Seckill::getIsDelete, 0));
        Map<Long, Integer> seckillMap = seckillList.stream().collect(Collectors.toMap(Seckill::getSeckillId, Seckill::getMaxNum));
        //获取退款的所有订单项
        List<String[]> list = new ArrayList<>(skuStockList.size());
        // max 等于-1时，不需要用到用户id，传个0就好了，减少数据量
        String defaultUserId = "0";
        for (SkuStockVO skuStockVO : skuStockList) {
            Integer max = seckillMap.getOrDefault(skuStockVO.getActivityId(), -1);
            list.add(StockUtil.loadQueryArray(
                    skuStockVO.getSkuId(),
                    skuStockVO.getStock(),
                    skuStockVO.getStockPointId(),
                    skuStockVO.getRefundId(),
                    skuStockVO.getActivityId(),
                    skuStockVO.getTime().getTime(),
                    skuStockVO.getStatus(),
                    max,
                    Objects.equals(max, -1) ? defaultUserId : skuStockVO.getUserId()
            ));
        }
        String s = stockManager.executeLuk(list, StockManager.SECKILL_ORDER_REFUND_STOCK_HANDLE_BYTES);
    }
}
